package cn.lastcc.pwdmanage.ui;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources.NotFoundException;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import cn.lastcc.pwdmanage.R;
import cn.lastcc.pwdmanage.core.CustomApp;
import cn.lastcc.pwdmanage.core.SerialUtil;
import cn.lastcc.pwdmanage.entity.IConstant;
import cn.lastcc.pwdmanage.entity.Info;

public class MainActivity extends Activity {

	public static MainActivity instance = null;

    private final long exitTime = 2000; // 两次按下后退键的间隔时间(毫秒)
    private long lastExitTime = 0; // 第一次点击返回按钮的时间(毫秒)

    // 声明控件
    private Button btnCreatePwd = null;
    private Button btnPwdList = null;
    private Button btnSetUserPwd = null;
    private Button btnAbout = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setTitle("管理界面");
        instance = this;
        setContentView(R.layout.activity_main);
        // Show the Up button in the action bar.
//        setupActionBar();
        // 根据 id 获得控件
        this.btnCreatePwd = (Button) this.findViewById(R.id.btnCreatePwd_main);
        this.btnPwdList = (Button) this.findViewById(R.id.btnPwdList_main);
        this.btnSetUserPwd = (Button) this.findViewById(R.id.btnSetUserPwd_main);
        this.btnAbout = (Button) this.findViewById(R.id.btnAbout_main);

        CustomApp customApp = (CustomApp) MainActivity.this.getApplication();

        Info info = null;
        try {
            info = SerialUtil.getInfo();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 如果 Info 文件不存在则不允许创建和管理密码
        if (null == info) {
            btnCreatePwd.setEnabled(false);
            btnPwdList.setEnabled(false);
        } else {
            Intent intent = this.getIntent();
            if (TextUtils.isEmpty(customApp.getUserPwd())) {
                customApp.setUserPwd(intent.getStringExtra(IConstant.LOGIN_PARAM_PWD_LBL));
            }
        }
        this.btnCreatePwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 启动创建密码窗口(CreatePwdActivity)
                Intent createPwdIntent = new Intent();
                createPwdIntent.setClass(MainActivity.this, CreatePwdActivity.class);
                startActivity(createPwdIntent);
            }
        });
        this.btnSetUserPwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 启动登录密码修改窗口(UserPwdModifyActivity)
                Intent userPwdModifyIntent = new Intent();
                userPwdModifyIntent.setClass(MainActivity.this, UserPwdModifyActivity.class);
                startActivity(userPwdModifyIntent);
            }
        });
        this.btnPwdList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 启动密码管理窗口(PwdListActivity)
                Intent pwdListIntent = new Intent();
                pwdListIntent.setClass(MainActivity.this, PwdListActivity.class);
                startActivity(pwdListIntent);
            }
        });
        this.btnAbout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    new AlertDialog.Builder(MainActivity.this)
                    .setTitle(R.string.str_about_title)
                    .setMessage(String.format(v.getResources().getString(R.string.app_about), v.getContext().getPackageManager().getPackageInfo(v.getContext().getPackageName() , 0).versionName))
                    .setPositiveButton(R.string.str_globe_OK, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .create().show();
                } catch (NotFoundException e) {
                    e.printStackTrace();
                    Toast.makeText(v.getContext(), R.string.msg_about_alertFailed, Toast.LENGTH_SHORT).show();
                } catch (NameNotFoundException e) {
                    e.printStackTrace();
                    Toast.makeText(v.getContext(), R.string.msg_about_alertFailed, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 双击后退键退出应用程序
        if ((keyCode == KeyEvent.KEYCODE_BACK) && (event.getAction() == KeyEvent.ACTION_DOWN)) {
            if ((System.currentTimeMillis() - this.lastExitTime) > this.exitTime) {
                Toast.makeText(this, R.string.msg_mainActivity_exitPrompt, Toast.LENGTH_SHORT).show();
                this.lastExitTime = System.currentTimeMillis();
            } else {
                // 退出应用程序
                this.finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * Set up the {@link android.app.ActionBar}, if the API is available.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void setupActionBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            getActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }
}
